// api/debugApi.ts

/**
 * RAG 调试和数据管理 API 封装
 * 对应后端 api/endpoints/debug_index.py
 */

import { initializeApiConfig } from './config';
const API_BASE = initializeApiConfig(); 

interface ErrorDetail {
  detail: string;
}

// 假设 handleResponse 函数存在
async function handleResponse<T>(response: Response): Promise<T> {
  if (!response.ok) {
    let errorDetail: ErrorDetail = { detail: '未知 API 错误' };
    try {
      errorDetail = await response.json();
    } catch (e) {
      const text = await response.text();
      errorDetail.detail = response.statusText + ': ' + text.substring(0, 100) + '...';
    }
    throw new Error(errorDetail.detail);
  }
  // 仅在响应有内容时解析JSON
  if (response.status !== 204 && response.headers.get('content-length') !== '0') {
      return response.json();
  }
  return {} as T; // 返回空对象以满足 Promise<T>
}

// --- 类型定义 ---
export interface NodeMetadata {
  [key: string]: any;
}

export interface IndexedNode {
  node_id: string;
  chroma_id: string;
  metadata: NodeMetadata;
  file_name: string;
  page_label: string;
  text: string;
  embedding: number[]; // 嵌入向量
}

export interface RetrievedNodeSnippet {
  score: number;
  node_id: string;
  text_snippet: string;
  metadata: NodeMetadata;
}

export interface Citation {
  sentence: string;
  referenced_chunk_id: string;
  referenced_chunk_text: string;
  document_id: number;
  material_id: number;
  file_name: string;
  page_label: string;
}

export interface DebugQueryResponse {
  query_text: string;
  final_llm_prompt: string;
  original_retrieved_nodes: RetrievedNodeSnippet[];
  final_retrieved_nodes: RetrievedNodeSnippet[];
  final_response_content: string;
  citations: Citation[];
}

export interface QueryRequestPayload {
  question: string;
  collection_name: string;
  // 以下为可选的过滤和调试参数
  target_file_ids?: string[]; // 后端需要字符串数组
  filters?: { [key: string]: any }; // ChromaDB filter 格式
  similarity_top_k?: number; // 初始召回 top_k (如果不同于默认配置)
}

// --- API 方法定义 ---
// 2. **查询 Collection 节点列表**
export const listIndexedNodes = async (
  collectionName: string,
  limit: number = 20,
  fileName?: string,
  chromaId?: string,
  title?: string
): Promise<IndexedNode[]> => {
  const params = new URLSearchParams({
    collection_name: collectionName,
    limit: String(limit),
  });
  if (fileName) params.append('file_name', fileName);
  if (chromaId) params.append('chroma_id', chromaId);
  if (title) params.append('title', title);

  const response = await fetch(`${API_BASE}/debug/indexed?${params.toString()}`);
  return handleResponse(response);
};

// 3. **查询单个节点**
export const getNodeById = async (
  collectionName: string,
  chromaId: string
): Promise<{ chroma_id: string, metadata: NodeMetadata, text: string }> => {
  const response = await fetch(`${API_BASE}/debug/indexed/${chromaId}?collection_name=${collectionName}`);
  return handleResponse(response);
};

// 4. **测试带过滤的召回**
export const debugRetrieveWithFilters = async (
  payload: QueryRequestPayload
): Promise<RetrievedNodeSnippet[]> => {
  const response = await fetch(`${API_BASE}/debug/retrieve-with-filters`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(payload),
  });
  return handleResponse(response);
};

// 5. **删除整个 Collection**
export const deleteEntireCollection = async (
  collectionName: string
): Promise<{ status: string, message: string }> => {
  const response = await fetch(`${API_BASE}/debug/delete-collection?collection_name=${collectionName}`, {
    method: 'DELETE',
  });
  return handleResponse(response);
};

// 6. **执行完整的 RAG 流程**
export const debugRagFlow = async (
  payload: QueryRequestPayload
): Promise<DebugQueryResponse> => {
  const response = await fetch(`${API_BASE}/debug/debug-rag-flow`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(payload),
  });
  return handleResponse(response);
};

// 7. **根据过滤器删除文档块**
export const deleteChunksByFilter = async (
  collectionName: string,
  materialId?: number,
  keyword?: string,
  docType?: string
): Promise<{ status: string, message: string }> => {
  const params = new URLSearchParams({
    collection_name: collectionName,
  });
  if (materialId !== undefined && materialId !== null) params.append('material_id', String(materialId));
  if (keyword) params.append('keyword', keyword);
  if (docType) params.append('doc_type', docType);

  if (!materialId && !keyword && !docType) {
    throw new Error("必须提供 material_id, keyword 或 doc_type 中的至少一个。");
  }

  const response = await fetch(`${API_BASE}/debug/delete-by-filter?${params.toString()}`, {
    method: 'POST', // 后端要求 POST/GET with Query Params
  });
  return handleResponse(response);
};

// 8. **查询文档块总数**
export const countChunks = async (
  collectionName: string
): Promise<{ collection_name: string, count: number, status: string }> => {
  const response = await fetch(`${API_BASE}/debug/count-chunks?collection_name=${collectionName}`);
  return handleResponse(response);
};